<template>
	<div class="wrapper">
		<!-- 顶部应用栏 -->
		<header class="mdc-top-app-bar">
			<div class="mdc-top-app-bar__row">
				<section class="mdc-top-app-bar__section mdc-top-app-bar__section--align-start">
					<BackButton />
					<h1 class="mdc-top-app-bar__title">交易流水</h1>
				</section>
			</div>
		</header>

		<!-- 筛选标签 -->
		<div class="filter-tabs">
			<button 
				v-for="tab in filterTabs" 
				:key="tab.value"
				class="tab-btn"
				:class="{ active: currentIndex === tab.value }"
				@click="switchTab(tab.value)"
			>
				{{ tab.label }}
			</button>
		</div>

		<!-- 交易列表 -->
		<div class="transaction-list">
			<div v-if="loading" class="loading">
				<p>加载中...</p>
			</div>
			<div v-else-if="transactions.length === 0" class="empty">
				<p>暂无交易记录</p>
			</div>
			<div v-else>
				<div 
					v-for="(trans, index) in transactions" 
					:key="index"
					class="transaction-item"
				>
					<div class="transaction-header">
						<div class="transaction-type">
							<div class="type-icon" :class="getAmountClass(trans)">
								<i class="material-icons">{{ getTransactionIcon(trans) }}</i>
							</div>
							<div class="type-info">
								<span class="type-name">{{ getTransactionType(trans) }}</span>
								<span class="type-desc">{{ getTransactionDesc(trans) }}</span>
							</div>
						</div>
						<div class="transaction-amount" :class="getAmountClass(trans)">
							{{ getAmountText(trans) }}
						</div>
					</div>
					<div class="transaction-details">
						<p class="transaction-time">{{ formatTime(trans.createTime) }}</p>
						<div class="transaction-status" v-if="trans.isFrozen || !trans.isValid">
							<span v-if="trans.isFrozen" class="status frozen">冻结中</span>
							<span v-if="!trans.isValid" class="status invalid">已失效</span>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 底部菜单部分 -->
		<AppFooter></AppFooter>
	</div>
</template>

<script>
	import AppFooter from '../components/AppFooter.vue';
	import BackButton from '../components/BackButton.vue';
	export default {
		name: 'WalletTransaction',
		data() {
			return {
				transactions: [],
				loading: false,
				user: null,
				currentIndex: 0, // 0-全部, 1-收入, 2-支出
				filterTabs: [
					{ label: '全部', value: 0 },
					{ label: '收入', value: 1 },
					{ label: '支出', value: 2 }
				]
			}
		},
		created() {
			let user = this.$getSessionStorage('user');
			if (user == null) {
				this.$router.push('/login');
				return;
			}
			this.user = user;
			this.loadTransactions();
		},
		methods: {
			switchTab(index) {
				if (this.currentIndex !== index) {
					this.currentIndex = index;
					this.loadTransactions();
				}
			},
			loadTransactions() {
				this.loading = true;
				// 后端 index: 0-全部, 1-收入, -1-支出
				// 前端 currentIndex: 0-全部, 1-收入, 2-支出
				let backendIndex = this.currentIndex;
				if (this.currentIndex === 2) {
					backendIndex = -1; // 支出
				}
				
				this.$axios.post('wallet/transInfo', this.$qs.stringify({
					walletId: this.user.userId,
					index: backendIndex
				})).then(response => {
					if (response.data && (response.data.code === 200 || response.data.code === '200')) {
						const result = response.data.result || [];
						// 确保数据格式正确
						this.transactions = Array.isArray(result) ? result.slice().sort((a, b) => {
							const aTime = a && a.createTime ? new Date(a.createTime).getTime() : 0;
							const bTime = b && b.createTime ? new Date(b.createTime).getTime() : 0;
							return bTime - aTime;
						}) : [];
						console.log('交易记录:', this.transactions);
					} else {
						const errorMsg = response.data?.message || '获取交易记录失败';
						console.error('获取交易记录失败:', errorMsg);
						this.$toast?.error(errorMsg);
						this.transactions = [];
					}
				}).catch(error => {
					console.error('获取交易记录失败:', error);
					const errorMsg = error.response?.data?.message || error.message || '获取交易记录失败';
					this.$toast?.error(errorMsg);
					this.transactions = [];
				}).finally(() => {
					this.loading = false;
				});
			},
			getTransactionType(trans) {
				// 判断交易类型
				if (!trans.fromWalletId || trans.fromWalletId === '' || trans.fromWalletId === null) {
					return '充值';
				} else if (!trans.toWalletId || trans.toWalletId === '' || trans.toWalletId === null) {
					return '提现';
				} else if (trans.fromWalletId === this.user.userId) {
					return '支付';
				} else if (trans.toWalletId === this.user.userId) {
					return '收款';
				} else {
					return '转账';
				}
			},
			getTransactionDesc(trans) {
				// 获取交易描述
				if (!trans.fromWalletId || trans.fromWalletId === '' || trans.fromWalletId === null) {
					return '账户充值';
				} else if (!trans.toWalletId || trans.toWalletId === '' || trans.toWalletId === null) {
					return '账户提现';
				} else if (trans.fromWalletId === this.user.userId) {
					return `支付给 ${trans.toWalletId}`;
				} else if (trans.toWalletId === this.user.userId) {
					return `来自 ${trans.fromWalletId}`;
				} else {
					return '转账';
				}
			},
			getTransactionIcon(trans) {
				// 使用 Material Icons
				if (!trans.fromWalletId || trans.fromWalletId === '' || trans.fromWalletId === null) {
					return 'add_circle';
				} else if (!trans.toWalletId || trans.toWalletId === '' || trans.toWalletId === null) {
					return 'remove_circle';
				} else if (trans.fromWalletId === this.user.userId) {
					return 'arrow_upward';
				} else {
					return 'arrow_downward';
				}
			},
			getAmountText(trans) {
				const amount = parseFloat(trans.amount || 0);
				const amountStr = amount.toFixed(2);
				if (!trans.fromWalletId || trans.fromWalletId === '' || trans.fromWalletId === null) {
					return `+¥${amountStr}`;
				} else if (!trans.toWalletId || trans.toWalletId === '' || trans.toWalletId === null) {
					return `-¥${amountStr}`;
				} else if (trans.fromWalletId === this.user.userId) {
					return `-¥${amountStr}`;
				} else {
					return `+¥${amountStr}`;
				}
			},
			getAmountClass(trans) {
				if (!trans.fromWalletId || trans.fromWalletId === '' || trans.fromWalletId === null) {
					return 'income';
				} else if (!trans.toWalletId || trans.toWalletId === '' || trans.toWalletId === null) {
					return 'expense';
				} else if (trans.fromWalletId === this.user.userId) {
					return 'expense';
				} else {
					return 'income';
				}
			},
			formatTime(timeStr) {
				if (!timeStr) return '';
				// 格式化时间显示
				try {
					const date = new Date(timeStr);
					const now = new Date();
					const diff = now - date;
					const days = Math.floor(diff / (1000 * 60 * 60 * 24));
					
					if (days === 0) {
						// 今天：显示时间
						const hours = date.getHours().toString().padStart(2, '0');
						const minutes = date.getMinutes().toString().padStart(2, '0');
						return `今天 ${hours}:${minutes}`;
					} else if (days === 1) {
						// 昨天
						const hours = date.getHours().toString().padStart(2, '0');
						const minutes = date.getMinutes().toString().padStart(2, '0');
						return `昨天 ${hours}:${minutes}`;
					} else if (days < 7) {
						// 一周内：显示星期
						const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
						const weekday = weekdays[date.getDay()];
						const hours = date.getHours().toString().padStart(2, '0');
						const minutes = date.getMinutes().toString().padStart(2, '0');
						return `周${weekday} ${hours}:${minutes}`;
					} else {
						// 更早：显示完整日期
						const year = date.getFullYear();
						const month = (date.getMonth() + 1).toString().padStart(2, '0');
						const day = date.getDate().toString().padStart(2, '0');
						const hours = date.getHours().toString().padStart(2, '0');
						const minutes = date.getMinutes().toString().padStart(2, '0');
						return `${year}-${month}-${day} ${hours}:${minutes}`;
					}
				} catch (e) {
					return timeStr;
				}
			}
		},
		components: {
			AppFooter,
			BackButton
		}
	}
</script>

<style scoped>
	/****************** 总容器 ******************/
	.wrapper {
		width: 100%;
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	/* 顶部应用栏 */
	.mdc-top-app-bar {
		background-color: #1976D2;
		color: white;
		position: sticky;
		top: 0;
		z-index: 100;
		box-shadow: 0 2px 4px rgba(0,0,0,0.1);
	}

	.mdc-top-app-bar__row {
		display: flex;
		align-items: center;
		height: 72px;
		padding: 0 20px;
	}

	.mdc-top-app-bar__section {
		display: flex;
		align-items: center;
		gap: 16px;
		flex-direction: row;
	}

	.mdc-top-app-bar__title {
		font-size: 22px;
		font-weight: 500;
		margin: 0;
		white-space: nowrap;
		line-height: 1;
	}

	/****************** 筛选标签 ******************/
	.filter-tabs {
		margin-top: 0;
		background-color: #fff;
		padding: 2vw 4vw;
		display: flex;
		gap: 2vw;
		box-shadow: 0 2px 4px rgba(0,0,0,0.05);
	}

	.tab-btn {
		flex: 1;
		padding: 2.5vw 4vw;
		border: none;
		background-color: #f5f5f5;
		color: #666;
		font-size: 3.5vw;
		border-radius: 8px;
		cursor: pointer;
		transition: all 0.3s;
	}

	.tab-btn.active {
		background-color: #0097FF;
		color: #fff;
		font-weight: 500;
	}

	.tab-btn:active {
		transform: scale(0.98);
	}

	/****************** 交易列表 ******************/
	.transaction-list {
		padding: 4vw;
		padding-bottom: 120px;
	}

	.loading, .empty {
		text-align: center;
		padding: 20vw 0;
		color: #999;
		font-size: 4vw;
	}

	.transaction-item {
		background-color: #fff;
		border-radius: 12px;
		padding: 4vw;
		margin-bottom: 3vw;
		box-shadow: 0 2px 8px rgba(0,0,0,0.1);
	}

	.transaction-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 2vw;
	}

	.transaction-type {
		display: flex;
		align-items: center;
		gap: 3vw;
		flex: 1;
	}

	.type-icon {
		width: 10vw;
		height: 10vw;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
	}

	.type-icon.income {
		background-color: #e8f5e9;
		color: #4caf50;
	}

	.type-icon.expense {
		background-color: #ffebee;
		color: #f44336;
	}

	.type-icon i {
		font-size: 5vw;
	}

	.type-info {
		display: flex;
		flex-direction: column;
		gap: 1vw;
		flex: 1;
	}

	.type-name {
		font-size: 4vw;
		color: #333;
		font-weight: 500;
	}

	.type-desc {
		font-size: 3vw;
		color: #999;
	}

	.transaction-amount {
		font-size: 5vw;
		font-weight: bold;
	}

	.transaction-amount.income {
		color: #4caf50;
	}

	.transaction-amount.expense {
		color: #f44336;
	}

	.transaction-details {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 2vw;
		padding-top: 2vw;
		border-top: 1px solid #f0f0f0;
	}

	.transaction-time {
		font-size: 3.5vw;
		color: #999;
		margin: 0;
	}

	.transaction-status {
		margin: 0;
	}

	.status {
		font-size: 3vw;
		padding: 1vw 2vw;
		border-radius: 4px;
	}

	.status.frozen {
		background-color: #ff9800;
		color: #fff;
	}

	.status.invalid {
		background-color: #999;
		color: #fff;
	}
</style>

